﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using BLL;
using Model;
using Common;
using System.Web.Script.Serialization;

namespace WebPortal.Controllers
{
    public class PEParaController : BaseController
    {
        public ActionResult DictionaryShow()
        {
            return View();
        }
        public ActionResult DictList()
        {
            return View();
        }
        public ActionResult DictModelType()
        {
            return View();
        }
        public ActionResult SysConfig()
        {
            return View();
        }
        public ActionResult QueryAnalyzer()
        {
            return View();
        }
        public ActionResult StructView()
        {
            return View();
        }
        public ActionResult Edit(string id, string dbName)
        {
            if (id == null)//添加页面
                return View(new Model.DictionaryInfo());
            else//修改页面
            {
                LoginInfo loginInfos = base.loginInfo();
                loginInfos.DBName = dbName;
                DictionaryBLL bll = new DictionaryBLL(loginInfos);
                DictionaryInfo model = bll.GetInfoById(id);
                return View(model);
            }
        }
        public ActionResult EditDict(string id, string dbName)
        {
            if (string.IsNullOrEmpty(id) || id.ToLower() == "undefined")//添加页面
                return View(new Model.DictionaryInfo());
            else//修改页面
            {
                LoginInfo loginInfos = base.loginInfo();
                DictionaryBLL bll = new DictionaryBLL(loginInfos);
                DictionaryInfo model = bll.GetDictById(id);
                return View(model);
            }
        }
        /// <summary>
        /// 数据列表
        /// </summary>
        /// <param name="name">名称</param>
        /// <param name="description">描述</param>
        /// <returns></returns>
        public ActionResult GetDictionaryList(string name, string ParentID)
        {
            string order = Request.Params["order"];
            string sort = Request.Params["sort"];
            if (string.IsNullOrEmpty(order))
                order = "asc";
            if (string.IsNullOrEmpty(sort))
                sort = "OrderNo";
            var sqlparams = new IDataParameter[2]
            {
                 new SqlParameter("@Name",  name)
                 ,new SqlParameter("@ParentID",  ParentID) 
            };

            LoginInfo loginInfos = base.loginInfo();
            DictionaryBLL bll = new DictionaryBLL(loginInfos);
            List<DictionaryInfo> rows = bll.GetList(sqlparams, sort, order);
            foreach (DictionaryInfo model in rows)
            {
                if (string.IsNullOrEmpty(ParentID))
                    model.Name = string.Format("<img src='/images/tree_folder.gif' /><a href='#' onclick='ViewList(\"{0}\",\"{1}\");'>{1}</a>", model.Guid, model.Name);
            }
            Dictionary<String, Object> jsonDict = new Dictionary<String, Object>();
            jsonDict.Add("total", rows.Count);
            jsonDict.Add("rows", rows);
            return Json(jsonDict);
        }
        public ActionResult GetParentList(string dbName, string name = "")
        {
            var sqlparams = new IDataParameter[1]
            {
                 new SqlParameter("@Name",  name) 
            };

            LoginInfo loginInfos = base.loginInfo();
            DictionaryBLL bll = new DictionaryBLL(loginInfos);
            List<DictionaryInfo> rows = bll.GetParentList(sqlparams);

            Dictionary<String, Object> jsonDict = new Dictionary<String, Object>();
            jsonDict.Add("total", rows.Count);
            jsonDict.Add("rows", rows);
            return Json(jsonDict);
        }
        public ActionResult GetSysConfig()
        {
            LoginInfo loginInfos = base.loginInfo();
            DictionaryBLL bll = new DictionaryBLL(loginInfos);
            string type = Request.Params["type"];
            List<SysConfig> rows = bll.GetSysConfig(type);

            return Json(rows);
        }
        public ActionResult GetUserIFConfig()
        {
            LoginInfo loginInfos = base.loginInfo();
            DictionaryBLL bll = new DictionaryBLL(loginInfos);
            List<UserIFConfig> rows = bll.GetUserIFConfig();
            return Json(rows);
        }
        public ActionResult GetDBDriverConfig()
        {
            LoginInfo loginInfos = base.loginInfo();
            DictionaryBLL bll = new DictionaryBLL(loginInfos);
            List<ETL_DBDriverConfig> rows = bll.GetDBDriverConfig();

            return Json(rows);
        }
        public ActionResult SaveDBDriverConfig()
        {
            LoginInfo loginInfos = base.loginInfo();
            DictionaryBLL bll = new DictionaryBLL(loginInfos);
            JavaScriptSerializer jsSerializer = new JavaScriptSerializer();
            ETL_DBDriverConfig dbModel = (ETL_DBDriverConfig)jsSerializer.Deserialize(Request.Params["query"], typeof(ETL_DBDriverConfig));
            SqlParameter[] para = new SqlParameter[] { 
            new SqlParameter("@SortNum",dbModel.SortNum)
            ,new SqlParameter("@DBType",dbModel.DBConfigName) 
            ,new SqlParameter("@ConnectionType",dbModel.ConnectionType)
            ,new SqlParameter("@DBContent",dbModel.DBContent)
            };
            return Json(bll.UpdateDBDriverConfig(para));
        }
        public ActionResult GetSysInfo()
        {
            string dbName = Request.Params["dbName"];
            string sysType = Request.Params["sysType"];
            LoginInfo loginInfos = base.loginInfo();
            loginInfos.DBName = dbName;
            DictionaryBLL bll = new DictionaryBLL(loginInfos);
            if (sysType == "1")
            {
                return Json(bll.GetSourceList());
            }
            else
            {
                return Json(bll.GetTargetList());
            }

        }
        private static EncrypCode encrypCode = new EncrypCode();
        public ActionResult RunSQL(string RunSQL, string DBName, string order, string sort)
        {
            LoginInfo loginInfos = base.loginInfo();
            loginInfos.DBName = DBName;
            DictionaryBLL bll = new DictionaryBLL(loginInfos);
            DataTable dt = new DataTable();
            try
            {
                string sysID = string.IsNullOrEmpty(Request.Params["sourceID"]) ? Request.Params["targetID"] : Request.Params["sourceID"];
                
                if (!string.IsNullOrEmpty(sysID))
                {
                    EtlSourceSystemBLL sourceSystemBLL = new EtlSourceSystemBLL(loginInfos);
                    ETLDbConfig dbConfig = sourceSystemBLL.GetDbConfigBySysID(sysID)[0];
                    string connstr = "";
                    string connType = "";

                    connstr = encrypCode.Decrypto(dbConfig.DbConnectionStr);//源系统数据库连接字符串
                    connType = dbConfig.DbType.ToString();//数据库类型
                    dt = bll.RunSQL(RunSQL, connType, connstr);
                }
                else
                {
                    dt = bll.RunSQL(RunSQL);
                }
                if (dt == null || dt.Rows.Count == 0)
                {
                    return Json("查询结果无数据。");
                }
                else
                {
                    if (string.IsNullOrEmpty(sort))
                        sort = "";
                    if (string.IsNullOrEmpty(order))
                        order = "";
                    return Json(SysPublicBLL.DataTableToString(dt, 0, order, sort, false, false, false));
                }
            }
            catch (Exception ex)
            {
                return Json(ex.Message);
            }

        }
        public ActionResult GetObjects(string s, string t, string c, int l, string DBName)
        {
            LoginInfo loginInfos = base.loginInfo();
            loginInfos.DBName = DBName;
            DictionaryBLL bll = new DictionaryBLL(loginInfos);
            string sysID = string.IsNullOrEmpty(Request.Params["sourceID"]) ? Request.Params["targetID"] : Request.Params["sourceID"];
            System.Text.StringBuilder res = new System.Text.StringBuilder();
            if (string.IsNullOrEmpty(sysID))
            {
                List<SQLObjects> rows = bll.GetObjects(s, t, c);
                int i = 0;
                foreach (SQLObjects sql in rows)
                {
                    switch (l)
                    {
                        case 1:
                            res.Append(string.Format("<div class='L{1}' onmouseover='lover(\"L{1}\")' onmouseout='lout(\"L{1}\")' onclick='lclick(\"L{1}\")'>{0}</div>", sql.Schema, i));
                            break;
                        case 2:
                            res.Append(string.Format("<div class='L{1}' onmouseover='lover(\"L{1}\")' onmouseout='lout(\"L{1}\")' onclick='lclick(\"L{1}\")'>{0}</div>", sql.ObjectName, i));
                            break;
                        case 3:
                            res.Append(string.Format("<div class='L{1}' onmouseover='lover(\"L{1}\")' onmouseout='lout(\"L{1}\")' onclick='lclick(\"L{1}\")'>{0}</div>", sql.ColumnName, i));
                            break;
                    }
                    i++;
                }
            }
            return Json(res.ToString());
        }
        /// <summary>
        /// 模型类型字典列表
        /// </summary>
        /// <param name="name">名称</param>
        /// <param name="description">描述</param>
        /// <returns></returns>
        public ActionResult DictModelTypeList(string dbName, string name = "", string Status = "")
        {
            var sqlparams = new IDataParameter[2]
            {
                 new SqlParameter("@Name",  name)
                ,new SqlParameter("@Status", Status)
            };

            LoginInfo loginInfos = base.loginInfo();
            loginInfos.DBName = dbName;
            DictionaryBLL bll = new DictionaryBLL(loginInfos);
            List<DictionaryInfo> rows = bll.GetMTList(sqlparams);
            Dictionary<String, Object> jsonDict = new Dictionary<String, Object>();
            jsonDict.Add("total", rows.Count);
            jsonDict.Add("rows", rows);
            return Json(jsonDict);
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id">字典id</param>
        /// <returns></returns>
        public ActionResult Delete(string id, string dbName)
        {
            LoginInfo loginInfos = base.loginInfo();
            DictionaryBLL bll = new DictionaryBLL(loginInfos);

            //new SysOperationLog(loginInfos).Log("字典配置", Request.UserHostAddress, OperationAction.删除, OperationStatus.成功, "删除字典配置信息操作,操作成功,ID=" + id, "superadmin");
            return Json(bll.Delete(id));
        }
        /// <summary>
        /// 保存数据
        /// </summary>
        /// <param name="model">字典model</param>
        /// <returns></returns>
        public int SaveData()
        {
            string query = Request.Params["query"];
            JavaScriptSerializer jsSerializer = new JavaScriptSerializer();
            DictionaryInfo model = (DictionaryInfo)jsSerializer.Deserialize(query, typeof(DictionaryInfo));

            int result = 0;
            bool IsUpdate = true;
            if (string.IsNullOrEmpty(model.Guid))
            {
                model.Guid = Guid.NewGuid().ToString();
                IsUpdate = false;
            }
            if (string.IsNullOrEmpty(model.ParentID))
            {
                model.ParentID = "";
            }
            SqlParameter[] sqlparam = new SqlParameter[]
             {
                    new SqlParameter("@GUID",model.Guid),
                    new SqlParameter("@Name",model.Name),
                    new SqlParameter("@Value",model.Value),
                    new SqlParameter("@Description",model.Description),
                    new SqlParameter("@OrderNo",model.OrderNo),
                    new SqlParameter("@ParentID",model.ParentID)
             };
            LoginInfo loginInfos = base.loginInfo();
            DictionaryBLL bll = new DictionaryBLL(loginInfos);

            if (IsUpdate)//更新
            {
                result = bll.Update(sqlparam);
                //new SysOperationLog(loginInfos).Log("字典配置", Request.UserHostAddress, OperationAction.更新, OperationStatus.成功, "更新字典配置信息操作,操作成功,ID=" + model.Guid, "superadmin");
            }
            else//新增
            {
                result = bll.Insert(sqlparam);
                //new SysOperationLog(loginInfos).Log("字典配置", Request.UserHostAddress, OperationAction.添加, OperationStatus.成功, "添加字典配置信息操作,操作成功,ID=" + model.Guid, "superadmin");
            }
            return result;
        }

        public ActionResult SaveSysConfig(string TimeOut, string TimeOutLot)
        {
            LoginInfo loginInfos = base.loginInfo();
            DictionaryBLL bll = new DictionaryBLL(loginInfos);

            return Json(bll.SaveSysConfig(TimeOut, TimeOutLot));
        }

        public ActionResult SaveSysConfigIFName(string IFName)
        {
            LoginInfo loginInfos = base.loginInfo();
            DictionaryBLL bll = new DictionaryBLL(loginInfos);

            return Json(bll.SaveSysConfig(IFName));
        }
        /// <summary>
        /// 删除模型分类
        /// </summary>
        /// <param name="id">字典id</param>
        /// <returns></returns>
        public int DeleteMT(string id, string dbName)
        {
            LoginInfo loginInfos = base.loginInfo();
            loginInfos.DBName = dbName;
            DictionaryBLL bll = new DictionaryBLL(loginInfos);

            new SysOperationLog(loginInfos).Log("模型分类字典配置", Request.UserHostAddress, OperationAction.删除, OperationStatus.成功, "删除模型分类字典配置信息操作,操作成功,ID=" + id, "superadmin");
            return bll.DeleteMT(id);
        }
        /// <summary>
        /// 保存数据模型分类
        /// </summary>
        /// <param name="model">字典model</param>
        /// <returns></returns>
        [HttpPost]
        public int SaveMTData(DictionaryInfo model, string dbName)
        {
            int result = 0;
            bool IsUpdate = true;
            if (string.IsNullOrEmpty(model.Guid))
            {
                model.Guid = Guid.NewGuid().ToString();
                IsUpdate = false;
            }
            if (string.IsNullOrEmpty(model.ParentID))
            {
                model.ParentID = "";
            }
            if (string.IsNullOrEmpty(model.Description))
                model.Description = "";
            if (string.IsNullOrEmpty(model.Value))
                model.Value = "";
            SqlParameter[] sqlparam = new SqlParameter[]
             {
                    new SqlParameter("@GUID",model.Guid),
                    new SqlParameter("@Name",model.Name),
                    new SqlParameter("@Value",model.Value),
                    new SqlParameter("@Description",model.Description),
                    new SqlParameter("@OrderNo",model.OrderNo),
                    new SqlParameter("@ParentID",model.ParentID)
             };
            LoginInfo loginInfos = base.loginInfo();
            loginInfos.DBName = dbName;
            DictionaryBLL bll = new DictionaryBLL(loginInfos);
            if (IsUpdate)//更新
            {
                result = bll.UpdateMT(sqlparam);
                new SysOperationLog(loginInfos).Log("模型分类字典配置", Request.UserHostAddress, OperationAction.更新, OperationStatus.成功, "更新字典配置信息操作,操作成功,ID=" + model.Guid, "superadmin");
            }
            else//新增
            {
                result = bll.InsertMT(sqlparam);
                new SysOperationLog(loginInfos).Log("模型分类字典配置", Request.UserHostAddress, OperationAction.添加, OperationStatus.成功, "添加字典配置信息操作,操作成功,ID=" + model.Guid, "superadmin");
            }
            return result;
        }

        /// <summary>
        /// 取字典列表
        /// </summary>
        /// <param name="keyName">字段名称</param>
        /// <returns></returns>
        public ActionResult DropDownList(string keyName, string dbName)
        {
            LoginInfo loginInfos = base.loginInfo();
            loginInfos.DBName = dbName;
            DictionaryBLL bll = new DictionaryBLL(loginInfos);
            return Json(bll.GetListByKeyName(keyName));
        }

        /// <summary>
        /// 取字典列表
        /// </summary>
        /// <param name="keyName">字段名称</param>
        /// <param name="value">值</param>
        /// <returns></returns>
        public string GetDictionaryName(string keyName, string value, string dbName)
        {
            LoginInfo loginInfos = base.loginInfo();
            loginInfos.DBName = dbName;
            DictionaryBLL bll = new DictionaryBLL(loginInfos);
            return bll.GetNameByKeyNameAndValue(keyName, value);
        }
        /// <summary>
        /// 取字典列表
        /// </summary>
        /// <param name="keyName">字段名称</param>
        /// <returns></returns>
        public List<SelectListItem> SelectList(string keyName, string dbName)
        {
            LoginInfo loginInfos = base.loginInfo();
            loginInfos.DBName = dbName;
            DictionaryBLL bll = new DictionaryBLL(loginInfos);
            IList<DictionaryInfo> list = bll.GetListByKeyName(keyName);
            List<SelectListItem> dropList = new List<SelectListItem>();

            foreach (DictionaryInfo model in list)
            {
                SelectListItem item = new SelectListItem();
                item.Text = model.Name;
                item.Value = model.Value;
                dropList.Add(item);
            }
            return dropList;
        }



        //public ActionResult UpdateState(string id, string state)
        //{
        //    var paras = new IDataParameter[2];
        //    paras[0] = new SqlParameter("@Guid", id);
        //    paras[1] = new SqlParameter("@State", state);
        //    var bll = new DictionaryBLL();
        //    return bll.UpdateState(paras);//更新状态
        //}
    }
}
